package conversion.Interceptor;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    // 设置每秒允许的最大请求数
    private static final double REQUESTS_PER_SECOND =3.0;

    // 创建一个RateLimiter实例
    private RateLimiter rateLimiter = RateLimiter.create(REQUESTS_PER_SECOND);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 尝试获取令牌
        String requestURI = request.getRequestURI();
        log.info(requestURI);
        if (rateLimiter.tryAcquire()) {
            // 获取到令牌，可以继续处理请求
            log.info("放行");
            return true;
        } else {
            // 未获取到令牌，请求被限制了
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            log.info("请求过多");
            response.getWriter().write("Too many requests. Please try again later.");
            return false;
        }
    }


}